import type {
  relevenceModalPropsType,
  relevenceFormValuesType,
  relevenceModalStateType,
  facilitySelectEnum
} from './typings'
import { defineComponent, ref, reactive } from 'vue'
import type { RuleItem } from 'async-validator'
import {
  ElDialog,
  ElButton,
  // ElIcon,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElMessageBox,
  ElLink
  // ElMessage
} from 'element-plus'
import type { FormInstance } from 'element-plus'
import ErrorRelevenceModal from './ErrorRelevenceModal'
import { useStore } from 'vuex'
import styles from '../../index.module.scss'
export default defineComponent({
  name: 'RelevenceModal',
  props: ['record', 'visible', 'cancel'],
  setup(props: relevenceModalPropsType) {
    const store = useStore()
    const count = ref()
    const devcount = ref()
    const state = reactive<relevenceModalStateType>({
      errorMessage: [],
      visible: false
    })
    const ruleFormRef = ref<FormInstance>()
    const relevenceForm = reactive<relevenceFormValuesType>({})
    const facilityType = ref([
      {
        name: '配电设施',
        id: '1'
      },
      {
        name: '灯杆',
        id: '2'
      }
    ])
    // 提交表单
    const handleCancelModal = () => {
      state.visible = !state.visible
    }
    const handleSubmitForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.validate(async (valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(relevenceForm))
          params.id = props?.record?.id
          params.facilityName = params.facilityName ? params.facilityName.replace(/\n/g, ',') : ''
          const res = await store.dispatch('roadManage/RelevenceDevInfo', params)
          if (res?.msg === '操作成功') {
            count.value = Object.keys(res.data)
            ElMessageBox({
              message: (
                <section class={styles['success-import-header']}>
                  {<p class="success-import-title'">关联成功</p>}
                  <p class={styles['success-relevence-content']}>
                    本次批量关联&nbsp;
                    <ElLink underline={false} type="primary">
                      {count.value[0] ?? 0}
                    </ElLink>
                    条数据
                  </p>
                </section>
              ),
              showCancelButton: false,
              confirmButtonText: '确认',
              cancelButtonClass: 'el-button--primary is-plain',
              closeOnClickModal: false, // 点遮罩层不关弹窗
              draggable: true // 可拖拽
            })
          } else {
            state.visible = !state.visible
            state.errorMessage = []
            Object.keys(res.data).forEach((key) => {
              state.errorMessage.push({ name: key, message: res.data[key] })
            })
          }
        } else {
          return false
        }
      })
    }
    // 校验
    const handleValidateName: RuleItem['asyncValidator'] = (rule, value, callback) => {
      if (!value) callback(new Error('请输入设施名称'))
      if (devcount.value > 500) callback(new Error('设施数量不能超过500个!'))
      callback()
    }
    // 设备名称数量
    const countChange = (value: string) => {
      if (!value.match(/\n/g)?.length && value) {
        devcount.value = 1
      } else if (value) {
        devcount.value = value.match(/\n{1,}/g)?.length
        const len = value.match(/(.*$)/g)?.length
        if (len! > 1) devcount.value += 1
      } else {
        devcount.value = 0
      }
    }
    // style={'max-width:460px'}
    return () => {
      return (
        <ElDialog
          title={'关联设施'}
          modelValue={!!props.visible}
          append-to-body
          width="42%"
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={props.cancel}
        >
          <ElForm ref={ruleFormRef} model={relevenceForm} labelWidth="120px" labelPosition="right">
            <ElFormItem
              prop="id"
              label="道路名称："
              class={styles['asset-home-area-search-bar-form-item']}
            >
              <div>{props?.record.name}</div>
            </ElFormItem>
            <ElFormItem
              prop="type"
              label="设施类型："
              class={styles['asset-home-area-search-bar-form-item']}
              rules={[{ required: true, message: '请选择设施类型', trigger: 'blur' }]}
            >
              <ElSelect
                v-model={relevenceForm.type}
                placeholder="请选择 设施类型"
                filterable
                clearable
              >
                {facilityType?.value.map((item: facilitySelectEnum) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.name!} />
                )) || []}
              </ElSelect>
            </ElFormItem>
            <ElFormItem
              prop="facilityName"
              label="设施名称："
              class={styles['asset-home-area-search-bar-form-item']}
              rules={[{ required: true, asyncValidator: handleValidateName }]}
            >
              <ElInput
                v-model={relevenceForm.facilityName}
                autosize={{ minRows: 6, maxRows: 11 }}
                type="textarea"
                placeholder="回车输入多个设施名称"
                clearable
                show-word-limit
                onInput={countChange}
              ></ElInput>
              <p class={styles.devNameCount}>{devcount.value ?? 0}/500</p>
            </ElFormItem>
          </ElForm>
          <div class={styles['confirm-button']}>
            <ElButton class={styles['confirm-button-cancel']} plain onClick={props.cancel}>
              取 消
            </ElButton>
            <ElButton
              class={styles['confirm-button-submit']}
              type="primary"
              onClick={() => handleSubmitForm(ruleFormRef.value)}
            >
              确 定
            </ElButton>
          </div>
          <ErrorRelevenceModal
            errorMessage={state.errorMessage}
            visible={state.visible}
            cancel={handleCancelModal}
          />
        </ElDialog>
      )
    }
  }
})
